package com.wangku.springmvc.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.wangku.springmvc.service.WxTokenService;
import com.wangku.springmvc.utils.AppResponse;
import com.wangku.springmvc.utils.Const;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Map;

/**
 * @description: 登录拦截器
 * @author: 李赛赛
 * @create: 2018-08-16 14:45
 **/
public class LoginInterceptor implements HandlerInterceptor {
    @Resource(name = "wxTokenService")
    private WxTokenService wxTokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String referer = request.getHeader("Referer");
        if (referer != null) {
            // System.out.println("referer---"+referer);
            URL url = new URL(referer);
            String refererHost = url.getProtocol() + "://" + url.getHost()
                    + ((url.getPort() == 80 || url.getPort() < 0) ? "" : (":" + url.getPort()));
            response.setHeader("Access-Control-Allow-Origin", refererHost);
        }
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        response.setHeader("Allow", "GET");

        // TODO Auto-generated method stub
        String path = request.getServletPath();
//		System.out.println(path.matches(Const.NO_INTERCEPTOR_PATH));
        if (path.matches(Const.NO_INTERCEPTOR_PATH)) {// 不需要登录的
            if (path.matches(Const.INTERCEPTOR_NO_REG)) {
                String tokens = request.getParameter(Const.DTOKEN_NAME);
                Map<String, String> token = wxTokenService.getToken(tokens);
                if (!token.isEmpty()) {
                    return true;
                } else {
                    String errMsg;

                    if (token == null || token.size() == 0) {
                        errMsg = "登录超时，请重新授权登录";
                    } else {
                        errMsg = "您的帐号尚未登录，请重新授权登录。";
                    }
                    responseOutWithJson(response, AppResponse.noPermission(errMsg));
                    return false;
                }
            } else {
                String tokens = request.getParameter(Const.DTOKEN_NAME);
                Map<String, String> token = wxTokenService.getToken(tokens);
                if (!token.isEmpty()) {
                    return true;
                } else {
                    String errMsg;

                    if (token == null || token.size() == 0) {
                        errMsg = "登录超时，请重新授权登录";
                    } else {
                        errMsg = "您的帐号尚未登录，请重新授权登录。";
                    }
                    responseOutWithJson(response, AppResponse.noPermission(errMsg));
                    return false;
                }
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
    protected void responseOutWithJson(HttpServletResponse response,
                                       AppResponse appResponse) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(JSONObject.toJSONString(appResponse));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                //out.close();
            }
        }
    }
}
